document.addEventListener('DOMContentLoaded', function() {
    // 元素引用
    const dropArea = document.getElementById('drop-area');
    const fileInput = document.getElementById('file-upload');
    const uploadedFilesContainer = document.getElementById('uploaded-files');
    const processFilesBtn = document.getElementById('process-files-btn');
    const processingResults = document.getElementById('processing-results');
    const webSearchToggle = document.getElementById('web-search-toggle');
    const singleRetrievalRadio = document.getElementById('single-retrieval');
    const hybridRetrievalRadio = document.getElementById('hybrid-retrieval');
    const messageInput = document.getElementById('message-input');
    const sendBtn = document.getElementById('send-btn');
    const chatContainer = document.getElementById('chat-container');
    const searchResults = document.getElementById('search-results');
    const tabButtons = document.querySelectorAll('.tab-btn');
    const tabContents = document.querySelectorAll('.tab-content');
    const exampleItems = document.querySelectorAll('.example-item');
    const clearChatBtn = document.getElementById('clear-chat-btn');
    const clearChatBtnRight = document.getElementById('clear-chat-btn-right');
    
    // 上传的文件数组
    let uploadedFiles = [];
    
    // 会话ID和历史记录
    let sessionId = null;
    let chatHistory = [];
    let isPending = false;
    
    // 支持的文件类型和对应的图标
    const fileTypeConfig = {
        'txt': { icon: '📄', color: '#4caf50', name: 'TXT' },
        'pdf': { icon: '📕', color: '#f44336', name: 'PDF' },
        'doc': { icon: '📘', color: '#2196f3', name: 'DOC' },
        'docx': { icon: '📘', color: '#2196f3', name: 'DOCX' }
    };
    
    // 初始化会话
    initializeSession();
    
    // 选项卡切换功能
    tabButtons.forEach(button => {
        button.addEventListener('click', () => {
            const tabId = button.getAttribute('data-tab');
            
            // 更新活动按钮
            tabButtons.forEach(btn => btn.classList.remove('active'));
            button.classList.add('active');
            
            // 更新活动内容
            tabContents.forEach(content => content.classList.remove('active'));
            document.getElementById(tabId).classList.add('active');
        });
    });
    
    // 示例问题功能
    exampleItems.forEach(example => {
        example.addEventListener('click', () => {
            messageInput.value = example.textContent;
            messageInput.focus();
        });
    });
    
    // 文件上传功能
    dropArea.addEventListener('click', () => {
        fileInput.click();
    });
    
    // 拖放事件
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        dropArea.addEventListener(eventName, preventDefaults, false);
        document.body.addEventListener(eventName, preventDefaults, false);
    });
    
    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }
    
    ['dragenter', 'dragover'].forEach(eventName => {
        dropArea.addEventListener(eventName, () => {
            dropArea.style.borderColor = '#adb5bd';
        dropArea.style.backgroundColor = '#f8f9fa';
        }, false);
    });
    
    ['dragleave', 'drop'].forEach(eventName => {
        dropArea.addEventListener(eventName, () => {
            dropArea.style.borderColor = '#ced4da';
            dropArea.style.backgroundColor = '';
        }, false);
    });
    
    dropArea.addEventListener('drop', handleDrop, false);
    
    function handleDrop(e) {
        const dt = e.dataTransfer;
        const files = dt.files;
        handleFiles(files);
    }
    
    fileInput.addEventListener('change', function() {
        handleFiles(this.files);
    });
    
    function handleFiles(files) {
        Array.from(files).forEach(file => {
            // 检查文件类型
            const fileExt = getFileExtension(file.name);
            if (!fileTypeConfig[fileExt]) {
                alert(`不支持的文件类型: ${file.name}\n支持的格式: TXT, PDF, DOC, DOCX`);
                return;
            }
            
            // 检查文件是否已经上传
            if (!uploadedFiles.some(f => f.name === file.name && f.size === file.size)) {
                uploadedFiles.push(file);
                displayFile(file);
            } else {
                alert(`文件 ${file.name} 已经上传过了`);
            }
        });
    }
    
    function getFileExtension(filename) {
        return filename.split('.').pop().toLowerCase();
    }
    
    function displayFile(file) {
        const fileItem = document.createElement('div');
        fileItem.className = 'file-item';
        
        const fileExt = getFileExtension(file.name);
        const fileConfig = fileTypeConfig[fileExt] || { icon: '📄', color: '#666', name: fileExt.toUpperCase() };
        
        const fileIcon = document.createElement('div');
        fileIcon.className = 'file-icon';
        fileIcon.textContent = fileConfig.icon;
        fileIcon.style.fontSize = '20px';
        fileIcon.style.marginRight = '10px';
        
        const fileInfo = document.createElement('div');
        fileInfo.className = 'file-info';
        fileInfo.style.flex = '1';
        
        const fileName = document.createElement('div');
        fileName.className = 'file-name';
        fileName.innerHTML = `
            <span class="file-type-indicator ${fileExt}" style="background-color: ${fileConfig.color};">
                ${fileConfig.name}
            </span>
            ${file.name}
        `;
        
        const fileSize = document.createElement('div');
        fileSize.className = 'file-size';
        fileSize.textContent = formatFileSize(file.size);
        
        const uploadStatus = document.createElement('div');
        uploadStatus.className = 'upload-status';
        uploadStatus.innerHTML = '<span style="color: #6c757d;">✓ 就绪</span>';
        
        fileInfo.appendChild(fileName);
        fileInfo.appendChild(fileSize);
        fileInfo.appendChild(uploadStatus);
        
        const fileActions = document.createElement('div');
        fileActions.className = 'file-actions';
        
        const removeButton = document.createElement('button');
        removeButton.innerHTML = '❌';
        removeButton.title = '移除文件';
        removeButton.style.background = 'none';
        removeButton.style.border = 'none';
        removeButton.style.cursor = 'pointer';
        removeButton.style.fontSize = '16px';
        removeButton.addEventListener('click', (e) => {
            e.stopPropagation();
            uploadedFiles = uploadedFiles.filter(f => f !== file);
            fileItem.remove();
        });
        
        fileActions.appendChild(removeButton);
        fileItem.appendChild(fileIcon);
        fileItem.appendChild(fileInfo);
        fileItem.appendChild(fileActions);
        uploadedFilesContainer.appendChild(fileItem);
    }
    
    function formatFileSize(bytes) {
        if (bytes < 1024) return bytes + ' B';
        else if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB';
        else if (bytes < 1073741824) return (bytes / 1048576).toFixed(1) + ' MB';
        else return (bytes / 1073741824).toFixed(1) + ' GB';
    }
    
    // 处理上传的文件
    processFilesBtn.addEventListener('click', () => {
        if (uploadedFiles.length === 0) {
            alert('请先上传文件');
            return;
        }
        
        // 更新文件状态为处理中
        updateFileStatus('processing');
        
        // 显示处理中状态
        processingResults.innerHTML = `
            <div class="status-result">
                <span class="loading"></span>
                <span class="status-text">正在处理 ${uploadedFiles.length} 个文件...</span>
            </div>
        `;
        
        const formData = new FormData();
        uploadedFiles.forEach(file => {
            formData.append('files', file);
        });
        
        fetch('/upload_files', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            // 显示处理结果
            displayProcessingResults(data.message);
            
            // 更新文件状态
            updateFileStatus('success');
            
            // 添加系统消息到对话
            addSystemMessage(`知识库已更新！成功处理了 ${uploadedFiles.length} 个文件，您可以开始提问了！`);
        })
        .catch(error => {
            console.error('Error:', error);
            updateFileStatus('error');
            processingResults.innerHTML = `
                <div class="status-result">
                    <span class="status-icon">❌</span>
                    <span class="status-text">文件处理失败，请重试</span>
                </div>
            `;
        });
    });
    
    function updateFileStatus(status) {
        const statusElements = document.querySelectorAll('.upload-status');
        statusElements.forEach(element => {
            element.className = `upload-status ${status}`;
            switch(status) {
                case 'processing':
                    element.innerHTML = '<span class="loading"></span><span>处理中...</span>';
                    break;
                case 'success':
                    element.innerHTML = '<span style="color: #6c757d;">✓ 已处理</span>';
                    break;
                case 'error':
                    element.innerHTML = '<span style="color: #dc3545;">✗ 处理失败</span>';
                    break;
            }
        });
    }
    
    function displayProcessingResults(message) {
        processingResults.innerHTML = '';
        
        if (typeof message === 'string') {
            // 处理单个消息
            if (message.includes('成功')) {
                processingResults.innerHTML = `
                    <div class="status-result">
                        <span class="status-icon">✅</span>
                        <span class="status-text">${message}</span>
                    </div>
                `;
            } else {
                processingResults.innerHTML = `
                    <div class="status-result">
                        <span class="status-icon">❌</span>
                        <span class="status-text">${message}</span>
                    </div>
                `;
            }
        } else if (Array.isArray(message)) {
            // 处理消息数组
            message.forEach(msg => {
                const icon = msg.includes('成功') ? '✅' : '❌';
                processingResults.innerHTML += `
                    <div class="status-result">
                        <span class="status-icon">${icon}</span>
                        <span class="status-text">${msg}</span>
                    </div>
                `;
            });
        }
    }
    
    // 初始化会话
    function initializeSession() {
        fetch('/create_session', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(response => response.json())
        .then(data => {
            sessionId = data.session_id;
            console.log('会话已创建，ID:', sessionId);
        })
        .catch(error => {
            console.error('创建会话失败:', error);
            // 添加系统消息通知用户
            addSystemMessage('连接服务器失败，请刷新页面重试');
        });
    }
    
    // 发送消息
    sendBtn.addEventListener('click', sendMessage);
    messageInput.addEventListener('keydown', function(e) {
        if (e.key === 'Enter' && e.ctrlKey) {
            sendMessage();
        }
    });
    
    function sendMessage() {
        if (isPending) {
            alert('请等待上一条消息回复完成');
            return;
        }
        
        const message = messageInput.value.trim();
        if (!message) {
            alert('请输入问题');
            return;
        }
        
        // 禁用输入和发送按钮
        isPending = true;
        sendBtn.disabled = true;
        messageInput.disabled = true;
        
        // 获取检索方式
        const retrievalMode = document.querySelector('input[name="rag-mode"]:checked').value;
        
        // 添加用户消息到对话
        addUserMessage(message);
        
        // 添加助手待处理消息
        const pendingMsgId = addPendingMessage();
        
        // 自动滚动到底部
        scrollToBottom();
        
        // 清空输入框
        messageInput.value = '';
        
        // 更新相关文档片段选项卡的内容
        const isHybridMode = retrievalMode === 'hybrid';
        searchResults.innerHTML = `
            <div class="search-section">
                <div class="search-section-title">
                    ${webSearchToggle.checked ? '🌐 联网搜索结果' : '🚫 联网搜索已关闭'}
                </div>
                <div id="web-search-content">
                    ${webSearchToggle.checked ? '<span class="loading"></span> 正在联网搜索...' : '未启用联网搜索'}
                </div>
            </div>
            
            <div class="search-section">
                <div class="search-section-title">
                    📚 本地知识库结果 ${isHybridMode ? '(混合检索模式)' : '(向量检索模式)'}
                </div>
                <div id="local-kb-content">
                    <span class="loading"></span> 正在检索本地知识库...
                </div>
            </div>
        `;
        
        // 检查是否使用流式输出
        const useStreaming = document.getElementById('use-streaming').checked;

        if (useStreaming) {
            // 流式输出逻辑
            const data = {
                message: message,
                session_id: sessionId,
                use_search: webSearchToggle.checked,
                retrieval_mode: retrievalMode
            };

            // 创建SSE连接
            const eventSource = new EventSource(`/stream_answer?data=${encodeURIComponent(JSON.stringify(data))}`);
            
            let answerElement = null;
            let timeoutId = null;

            eventSource.onmessage = function(event) {
                try {
                    const chunkData = JSON.parse(event.data);

                    if (chunkData.chunk) {
                        // 更新待处理消息
                        updatePendingMessage(pendingMsgId, chunkData.chunk, true);
                    }

                    if (chunkData.done) {
                        console.log('流式回答完成，移除加载状态');
                        // 移除加载状态
                        const pendingElement = document.getElementById(pendingMsgId);
                        if (pendingElement) {
                            pendingElement.classList.remove('pending-message');
                            console.log('已移除pending-message类');
                        }
                        // 清除超时
                        if (timeoutId) clearTimeout(timeoutId);
                        eventSource.close();
                        resetSendState();
                    }

                    if (chunkData.error) {
                        console.log('流式回答错误，移除加载状态');
                        // 清除超时
                        if (timeoutId) clearTimeout(timeoutId);
                        updatePendingMessage(pendingMsgId, `错误: ${chunkData.error}`);
                        // 移除加载状态
                        const pendingElement = document.getElementById(pendingMsgId);
                        if (pendingElement) {
                            pendingElement.classList.remove('pending-message');
                            console.log('错误情况下移除pending-message类');
                        }
                        eventSource.close();
                        resetSendState();
                    }
                } catch (error) {
                    console.error('解析SSE数据失败:', error);
                    // 清除超时
                    if (timeoutId) clearTimeout(timeoutId);
                    // 移除加载状态
                    const pendingElement = document.getElementById(pendingMsgId);
                    if (pendingElement) {
                        pendingElement.classList.remove('pending-message');
                        console.log('解析错误情况下移除pending-message类');
                    }
                    eventSource.close();
                    resetSendState();
                }
            };

            eventSource.onerror = function(error) {
                console.error('SSE连接错误:', error);
                // 清除超时
                if (timeoutId) clearTimeout(timeoutId);
                updatePendingMessage(pendingMsgId, '流式请求失败，请重试');
                // 移除加载状态
                const pendingElement = document.getElementById(pendingMsgId);
                if (pendingElement) {
                    pendingElement.classList.remove('pending-message');
                    console.log('SSE错误情况下移除pending-message类');
                }
                eventSource.close();
                resetSendState();
            };
            
            // 设置超时检查，确保加载状态最终会被移除
            timeoutId = setTimeout(() => {
                const pendingElement = document.getElementById(pendingMsgId);
                if (pendingElement && pendingElement.classList.contains('pending-message')) {
                    pendingElement.classList.remove('pending-message');
                    console.log('超时自动移除加载状态');
                }
            }, 30000); // 30秒超时
        } else {
            // 传统非流式请求
            fetch('/conversation', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    message: message,
                    session_id: sessionId,
                    use_search: webSearchToggle.checked,
                    retrieval_mode: retrievalMode
                })
            })
            .then(response => response.json())
            .then(data => {
                // 更新会话ID
                if (data.session_id) {
                    sessionId = data.session_id;
                }
                
                // 更新助手消息
                if (data.answer) {
                    updatePendingMessage(pendingMsgId, data.answer);
                } else {
                    updatePendingMessage(pendingMsgId, '未获取到回答，请重试');
                }
                
                resetSendState();
                scrollToBottom();
            })
            .catch(error => {
                console.error('初始化对话失败:', error);
                updatePendingMessage(pendingMsgId, '连接服务器失败，请重试');
                resetSendState();
            });
        }
        
        // 同时开始获取本地知识库和联网搜索结果
        const localKBContent = document.getElementById('local-kb-content');
        const webSearchContent = document.getElementById('web-search-content');
        
        // 1. 获取本地知识库结果
        fetch('/check_conversation_progress', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                message: message,
                session_id: sessionId,
                use_search: webSearchToggle.checked,
                type: 'local_kb',
                retrieval_mode: retrievalMode
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                localKBContent.innerHTML = formatLocalKBResults(data.local_kb_html, retrievalMode);
            } else {
                localKBContent.innerHTML = "❌ 检索失败";
            }
        })
        .catch(error => {
            console.error('本地知识库查询失败:', error);
            localKBContent.innerHTML = "❌ 检索失败";
        });
        
        // 2. 获取联网搜索结果
        if (webSearchToggle.checked) {
            fetch('/check_conversation_progress', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    message: message,
                    session_id: sessionId,
                    use_search: true,
                    type: 'web_search',
                    retrieval_mode: retrievalMode
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    webSearchContent.innerHTML = formatWebSearchResults(data.web_search_html);
                } else {
                    webSearchContent.innerHTML = "❌ 联网搜索失败";
                }
            })
            .catch(error => {
                console.error('联网搜索查询失败:', error);
                webSearchContent.innerHTML = "❌ 联网搜索失败";
            });
        }
        
        // 仅在非流式模式下获取AI回答
        if (!useStreaming) {
            // 3. 获取AI回答
            fetch('/check_conversation_progress', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    message: message,
                    session_id: sessionId,
                    use_search: webSearchToggle.checked,
                    type: 'answer',
                    retrieval_mode: retrievalMode
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    // 更新助手消息
                    updatePendingMessage(pendingMsgId, data.answer);

                    // 更新对话历史
                    if (data.history) {
                        chatHistory = data.history;
                    }

                    // 显示检索模式提示
                    if (retrievalMode === 'hybrid') {
                        setTimeout(() => {
                            addSystemMessage('💡 本次回答使用了混合检索模式，结合了向量检索和关键词检索的结果');
                        }, 500);
                    }
                } else {
                    updatePendingMessage(pendingMsgId, "❌ 生成回答失败，请重试");
                }

                // 重置状态
                resetSendState();

                // 自动滚动到底部
                scrollToBottom();
            })
            .catch(error => {
                console.error('AI回答查询失败:', error);
                updatePendingMessage(pendingMsgId, "❌ 生成回答失败，请重试");

                // 重置状态
                resetSendState();
            });
        }
    }
    
    function resetSendState() {
        isPending = false;
        sendBtn.disabled = false;
        messageInput.disabled = false;
        messageInput.focus();
    }
    
    function formatLocalKBResults(html, retrievalMode) {
        if (!html || html.includes('无相关内容')) {
            return '📭 本地知识库中没有找到相关内容';
        }
        
        // 添加检索模式说明
        const modeInfo = retrievalMode === 'hybrid' ? 
            '<div class="mode-info">🔀 混合检索：结合向量检索和关键词检索</div>' : 
            '<div class="mode-info">🎯 向量检索：基于语义相似度</div>';
        
        return modeInfo + html;
    }
    
    function formatWebSearchResults(html) {
        if (!html || html.includes('无结果') || html.includes('失败')) {
            return '🌐 联网搜索未找到相关信息';
        }
        
        return `<div class="web-search-content">${html}</div>`;
    }
    
    // 添加用户消息
    function addUserMessage(content) {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'message user-message';
        
        const now = new Date();
        const timeStr = now.toLocaleTimeString();
        
        messageDiv.innerHTML = `
            <div class="message-bubble">
                ${formatText(content)}
                <div class="message-time">${timeStr}</div>
            </div>
        `;
        
        chatContainer.appendChild(messageDiv);
        scrollToBottom();
    }
    
    // 添加助手消息
    function addAssistantMessage(content, isPending = false) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message assistant-message ${isPending ? 'pending-message' : ''}`;
        
        const now = new Date();
        const timeStr = now.toLocaleTimeString();
        
        const msgId = 'msg-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9);
        messageDiv.id = msgId;
        
        messageDiv.innerHTML = `
            <div class="message-bubble">
                ${formatText(content)}
                <div class="message-time">${timeStr}</div>
            </div>
        `;
        
        chatContainer.appendChild(messageDiv);
        scrollToBottom();
        
        return msgId;
    }
    
    // 添加待处理消息
    function addPendingMessage() {
        return addAssistantMessage('🤔 正在思考中...', true);
    }
    
    // 更新待处理消息
    function updatePendingMessage(msgId, content, isStreaming = false) {
        const messageDiv = document.getElementById(msgId);
        if (messageDiv) {
            if (!isStreaming) {
                messageDiv.classList.remove('pending-message');
            }
            
            const messageBubble = messageDiv.querySelector('.message-bubble');
            const timeElement = messageDiv.querySelector('.message-time');
            const timeStr = timeElement ? timeElement.textContent : new Date().toLocaleTimeString();
            
            // 流式模式下追加内容
            if (isStreaming) {
                // 获取现有内容（不含时间戳）
                let currentContent = messageBubble.innerHTML;
                // 移除时间戳部分
                currentContent = currentContent.replace(/<div class="message-time">.*?<\/div>/, '').trim();
                // 追加新内容
                messageBubble.innerHTML = `
                    ${currentContent}${formatText(content)}
                    <div class="message-time">${timeStr}</div>
                `;
            } else {
                // 非流式模式下替换内容
                messageBubble.innerHTML = `
                    ${formatText(content)}
                    <div class="message-time">${timeStr}</div>
                `;
            }
        }
        
        scrollToBottom();
    }
    
    // 添加系统消息
    function addSystemMessage(content) {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'system-message';
        
        messageDiv.innerHTML = `
            <div class="message-content">
                ${content}
            </div>
        `;
        
        chatContainer.appendChild(messageDiv);
        scrollToBottom();
    }
    
    // 清空对话
    clearChatBtn.addEventListener('click', clearChat);
    clearChatBtnRight.addEventListener('click', clearChat);
    
    function clearChat() {
        if (confirm('确定要清空当前对话吗？')) {
            // 清空对话容器，保留系统欢迎消息
            chatContainer.innerHTML = `
                <div class="system-message">
                    <div class="message-content">
                        你好！我是智能知识库助手，请问有什么我可以帮助你的吗？
                    </div>
                </div>
            `;
            
            // 清空搜索结果
            searchResults.innerHTML = '<p class="placeholder">提交问题后显示相关文档片段</p>';
            
            // 重新初始化会话
            initializeSession();
        }
    }
    
    // 自动滚动到底部（带平滑动画）
    function scrollToBottom() {
        chatContainer.scrollTo({
            top: chatContainer.scrollHeight,
            behavior: 'smooth'
        });
    }
    
    // 节流函数
    function throttle(func, limit) {
        let inThrottle;
        return function() {
            const args = arguments;
            const context = this;
            if (!inThrottle) {
                func.apply(context, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        }
    }
    
    // 优化滚动事件
    const throttledScrollToBottom = throttle(scrollToBottom, 100);
    
    // 格式化文本，处理换行和强调
    function formatText(text) {
        if (!text) return '';
        
        // 简化换行处理，避免过度分段
        return text
            .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
            .replace(/\*(.*?)\*/g, '<em>$1</em>')
            .replace(/\n/g, '<br>');
    }
    
    // 检索模式变化监听
    document.querySelectorAll('input[name="rag-mode"]').forEach(radio => {
        radio.addEventListener('change', function() {
            const mode = this.value;
            const description = mode === 'hybrid' ? 
                '混合检索将同时使用向量检索和关键词检索，并智能融合结果' : 
                '单一检索仅使用向量语义检索';
            
            // 可以在这里添加模式切换提示
            console.log(`检索模式已切换为: ${mode === 'hybrid' ? '混合检索' : '单一检索'}`);
        });
    });
    
    // 页面可见性变化监听（用户切换标签页时暂停某些操作）
    document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
            console.log('页面已隐藏');
        } else {
            console.log('页面已显示');
        }
    });
    
    // 错误处理
    window.addEventListener('error', function(e) {
        console.error('JavaScript错误:', e.error);
        // 可以在这里添加错误报告逻辑
    });
    
    // 网络状态监听
    window.addEventListener('online', function() {
        addSystemMessage('🌐 网络连接已恢复');
    });
    
    window.addEventListener('offline', function() {
        addSystemMessage('⚠️ 网络连接已断开，部分功能可能不可用');
    });
});

// 添加SSE流式提问函数
function streamAskQuestion(question, sessionId, useSearch, retrievalMode) {
    const conversationContainer = document.getElementById('conversation-container');
    const thinkingDiv = document.createElement('div');
    thinkingDiv.className = 'message assistant-message thinking';
    thinkingDiv.innerHTML = '<div class="message-content"><div class="typing-indicator"><span></span><span></span><span></span></div></div>';
    conversationContainer.appendChild(thinkingDiv);
    conversationContainer.scrollTop = conversationContainer.scrollHeight;

    // 准备数据
    const data = {
        message: question,
        session_id: sessionId,
        use_search: useSearch,
        retrieval_mode: retrievalMode
    };

    // 创建SSE连接
    const eventSource = new EventSource(`/stream_answer?data=${encodeURIComponent(JSON.stringify(data))}`);

    let answerElement = null;
    let fullAnswer = '';
    let timeoutId = null;

    // 处理消息事件
    eventSource.onmessage = function(event) {
        try {
            const data = JSON.parse(event.data);

            // 移除"正在思考"提示
            if (thinkingDiv) {
                thinkingDiv.remove();
                thinkingDiv = null;
            }

            // 创建回答元素（如果尚未创建）
            if (!answerElement) {
                answerElement = document.createElement('div');
                answerElement.className = 'message assistant-message pending-message';
                answerElement.innerHTML = '<div class="message-content"></div>';
                conversationContainer.appendChild(answerElement);

                // 立即设置超时检查，确保加载状态最终会被移除
                timeoutId = setTimeout(() => {
                    if (answerElement && answerElement.classList.contains('pending-message')) {
                        answerElement.classList.remove('pending-message');
                        console.log('超时自动移除加载状态');
                    }
                }, 30000); // 30秒超时
            }

            // 处理流式数据
            if (data.chunk) {
                fullAnswer += data.chunk;
                // 使用formatText处理内容，确保格式正确
                const formattedContent = formatText(fullAnswer);
                answerElement.querySelector('.message-content').innerHTML = formattedContent;
                conversationContainer.scrollTop = conversationContainer.scrollHeight;
            }

            // 处理完成事件
            if (data.done) {
                console.log('接收到完成信号，移除加载状态');
                // 先移除加载状态再关闭连接
                if (answerElement) {
                    answerElement.classList.remove('pending-message');
                    console.log('已移除pending-message类');
                }
                // 清除超时
                if (timeoutId) clearTimeout(timeoutId);
                eventSource.close();
            }

            // 处理错误
            if (data.error) {
                console.log('接收到错误信号，移除加载状态');
                // 清除超时
                if (timeoutId) clearTimeout(timeoutId);
                if (answerElement) {
                    answerElement.querySelector('.message-content').textContent = `错误: ${data.error}`;
                    answerElement.classList.remove('pending-message');
                    console.log('已移除pending-message类');
                }
                eventSource.close();
            }
        } catch (error) {
            console.error('解析SSE数据失败:', error);
            // 清除超时
            if (timeoutId) clearTimeout(timeoutId);
            // 移除加载状态
            if (answerElement) {
                answerElement.classList.remove('pending-message');
                console.log('错误情况下移除加载状态');
            }
            eventSource.close();
        }
    };

    // 处理错误
    eventSource.onerror = function(error) {
        console.error('SSE连接错误:', error);
        // 清除超时
        if (timeoutId) clearTimeout(timeoutId);
        if (thinkingDiv) {
            thinkingDiv.remove();
        }
        if (!answerElement) {
            answerElement = document.createElement('div');
            answerElement.className = 'message assistant-message error';
            answerElement.innerHTML = '<div class="message-content">流式请求失败，请重试</div>';
            conversationContainer.appendChild(answerElement);
        } else {
            answerElement.querySelector('.message-content').textContent += '\n\n流式请求中断';
            answerElement.classList.remove('pending-message');
            console.log('错误处理中移除加载状态');
        }
        conversationContainer.scrollTop = conversationContainer.scrollHeight;
        eventSource.close();
    };

    // 添加连接关闭监听，确保移除加载状态
    eventSource.onclose = function() {
        // 确保连接关闭时移除加载状态
        if (answerElement && answerElement.classList.contains('pending-message')) {
            answerElement.classList.remove('pending-message');
            console.log('连接关闭时移除加载状态');
        }
        // 清除超时
        if (timeoutId) clearTimeout(timeoutId);
        console.log('SSE连接已关闭，检查加载状态');
        // 清除超时
        if (timeoutId) clearTimeout(timeoutId);
        if (answerElement && answerElement.classList.contains('pending-message')) {
            answerElement.classList.remove('pending-message');
            console.log('连接关闭时移除加载状态');
        }
    };
}

// 修改现有提问函数，添加流式选项
function askQuestion() {
    const questionInput = document.getElementById('question-input');
    const question = questionInput.value.trim();
    if (!question) return;

    // 清空输入框
    questionInput.value = '';

    // 获取当前会话ID
    let sessionId = localStorage.getItem('sessionId');
    if (!sessionId) {
        // 创建新会话
        fetch('/create_session', {
            method: 'POST'
        })
        .then(response => response.json())
        .then(data => {
            sessionId = data.session_id;
            localStorage.setItem('sessionId', sessionId);
            sendQuestion(question, sessionId);
        })
        .catch(error => {
            console.error('创建会话失败:', error);
            addMessage('assistant', '创建会话失败，请重试');
        });
    } else {
        sendQuestion(question, sessionId);
    }
}

// 分离发送问题的逻辑
function sendQuestion(question, sessionId) {
    // 获取联网搜索状态
    const useSearch = document.getElementById('web-search-toggle').checked;
    
    // 获取检索模式
    let retrievalMode = 'single';
    if (document.getElementById('hybrid-retrieval').checked) {
        retrievalMode = 'hybrid';
    }
    
    // 获取流式输出状态
    const useStreaming = document.getElementById('use-streaming').checked;

    // 添加用户消息
    addMessage('user', question);

    // 选择使用流式还是非流式
    if (useStreaming) {
        streamAskQuestion(question, sessionId, useSearch, retrievalMode);
    } else {
        // 原有的非流式请求逻辑
        fetch('/conversation', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                message: question,
                session_id: sessionId,
                use_search: useSearch,
                retrieval_mode: retrievalMode
            })
        })
        .then(response => response.json())
        .then(data => {
            addMessage('assistant', data.answer);
        })
        .catch(error => {
            console.error('提问失败:', error);
            addMessage('assistant', '提问失败，请重试');
        });
    }
}